package com.tidy.seed.exception;

import com.tidy.seed.common.Result;
import com.tidy.seed.common.StatusCode;
import com.tidy.seed.admin.system.service.ErrorLogService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalException {
    @Resource
    private ErrorLogService errorLogService;

    // 处理自定义的 BaseException
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(HttpServletRequest request, BaseException ex) {
        errorLogService.saveErrorLog(request, ex.getCode(), ex.getMessage());
        int code = ex.getCode() != null ? ex.getCode() : StatusCode.CODE_500;
        return Result.fail(code, ex.getMessage());
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getField())
                    .append(":")
                    .append(fieldError.getDefaultMessage())
                    .append(";");
        }
        errorLogService.saveErrorLog(request, StatusCode.CODE_400, errorMsg.toString());
        return Result.fail(StatusCode.CODE_400, errorMsg.toString());
    }

    // 兜底异常
    @ExceptionHandler(Exception.class)
    public Result handleException(HttpServletRequest request, Exception ex) {
        errorLogService.saveErrorLog(request, StatusCode.CODE_500, ex.getMessage());
        ex.printStackTrace();
        String safeMessage = (ex.getMessage() == null || ex.getMessage().trim().isEmpty())
                ? ex.toString()
                : ex.getMessage();
        return Result.fail("服务器内部错误：" + safeMessage);
    }
}
